import os


class FileModification:

    def read_path(self, path='', plugin=''):
        # 在下面的代码行中使用断点来调试脚本。
        if path == '':
            path = 'D:\\phpstudy_pro\\WWW\\shop\\plugins\\' + plugin
        else:
            path = path;

        path_list = os.listdir(path)

        file_list = []
        for i in path_list:
            if i == '.git':
                continue
            if os.path.isdir(path + '\\' + i):
                file_list += self.read_path(path + '\\' + i)
            else:
                if (i.find('.php') == -1) and (i.find('.json') == -1):
                    continue
                file_list.append(path + '\\' + i)
        return file_list

    def replace_keywords(self, file_list, ord_key, new_key):
        count = 0
        for i in file_list:
            try:
                with open(i, 'rb') as f:
                    str_f = f.read().decode()
                    if str_f.find(ord_key) == -1:
                        continue
                    str_f2 = str_f.replace(ord_key, new_key)
                with open(i, 'wb') as f:
                    print(str_f2)
                    f.write(str_f2.encode())
                    count += 1
            except UnicodeDecodeError:
                with open(i, 'wb', encoding='utf-8') as f:
                    str_f = f.read().decode()
                    if str_f.find(ord_key) == -1:
                        continue
                    str_f2 = str_f.replace(ord_key, new_key)
                with open(i, 'wb', encoding='utf-8') as f:
                    print(str_f2)
                    f.write(str_f2.encode())
                    count += 1
        return count
